import pathlib
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTableWidgetItem, QApplication
from PyQt5.QtCore import QTranslator
from classes.engine import Engine
from ui_py.page5_ui import Main_Ui
from temp import Excel, ReadExcel
from grap import *
import json
from expert import Expert
from validation import validation
from error import Error
from dataExpert import Data
class Page5(QtWidgets.QWidget, Main_Ui):
    engine = Engine()
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.setupUi(self)
        with open('lang.json', encoding='utf-8') as file:
            data = json.load(file)
        if data['lang'] != "":
            self.trans = QTranslator(self)
            self.trans.load('translate/' + 'page5')
            _app = QApplication.instance() # получить экземпляр приложения
            _app.installTranslator(self.trans)
        self.lw = ""
        self.expert = Expert()
        self.err = Error()
        self.data = Data()
        self.err.clear = 0
        if data['lang'] != "":
            page = data['en']['page5']
            self.comboBox_3.addItem(page['lw'])
            self.comboBox_3.setCurrentText(page['lw'])
            self.comboBox_3.addItem(page['lw1'], 1)
            self.comboBox_3.addItem(page['lw2'], 2)
            self.comboBox.addItem(page['nw'])
            self.comboBox.setCurrentText(page['nw'])
            self.comboBox.addItem(page['nw1'], 0)
            self.comboBox.addItem(page['nw2'], 1)
            self.comboBox.addItem(page['nw3'], 2)
            self.comboBox.addItem(page['nw4'], 3)
            self.comboBox_2.addItem(page['ms'])
            self.comboBox_2.setCurrentText(page['ms'])
            self.comboBox_2.addItem(page['ms1'], 8)
            self.comboBox_2.addItem(page['ms2'], 10)
            self.comboBox_2.addItem(page['ms3'], 12)
            self.comboBox_2.addItem(page['ms4'], 16)
        else:
            self.comboBox_3.addItem("Выберите")
            self.comboBox_3.setCurrentText("Выберите")
            self.comboBox_3.addItem("Да", 1)
            self.comboBox_3.addItem("Нет", 2)
            self.comboBox.addItem("Выберите вариант канавки")
            self.comboBox.setCurrentText("Выберите вариант канавки")
            self.comboBox.addItem("Без канавки", 0)
            self.comboBox.addItem("С кольцевой канавкой", 1)
            self.comboBox.addItem("Верхний вкладыш с канавкой, нижний - без канавки", 2)
            self.comboBox.addItem("Неполная канавка", 3)
            self.comboBox_2.addItem("Выберите тип масла")
            self.comboBox_2.setCurrentText("Выберите тип масла")
            self.comboBox_2.addItem("SAE20", 8)
            self.comboBox_2.addItem("SAE30", 10)
            self.comboBox_2.addItem("SAE40", 12)
            self.comboBox_2.addItem("SAE50", 16)
        # self.comboBox_3.currentIndexChanged.connect(self.handleActivated)
        self.comboBox.currentIndexChanged.connect(self.construct)
        try:
            self.comboBox_3.blockSignals(True)
            if self.data.excel['lw'] == 1:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_3.setCurrentText(page['lw1'])
                else:
                    self.comboBox_3.setCurrentText("Да")
            else:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_3.setCurrentText(page['lw2'])
                else:
                    self.comboBox_3.setCurrentText("Нет")
            self.comboBox_3.blockSignals(False)
        except:
            pass
        try:
            self.comboBox.blockSignals(True)
            if self.data.excel['nw'] == 0:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox.setCurrentText(page['nw1'])
                else:
                    self.comboBox.setCurrentText("Без канавки")
            elif self.data.excel['nw'] == 1:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox.setCurrentText(page['nw2'])
                else:
                    self.comboBox.setCurrentText("С кольцевой канавкой")
            elif self.data.excel['nw'] == 2:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox.setCurrentText(page['nw3'])
                else:
                    self.comboBox.setCurrentText("Верхний вкладыш с канавкой, нижний - без канавки")
            elif self.data.excel['nw'] == 3:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox.setCurrentText(page['nw4'])
                else:
                    self.comboBox.setCurrentText("Неполная канавка")
            self.comboBox.blockSignals(False)
        except:
            pass
        try:
            self.comboBox_2.blockSignals(True)
            if self.data.excel['ms'] == 8:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_2.setCurrentText(page['ms1'])
                else:
                    self.comboBox_2.setCurrentText("SAE20")
            elif self.data.excel['ms'] == 10:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_2.setCurrentText(page['ms2'])
                else:
                    self.comboBox_2.setCurrentText("SAE30")
            elif self.data.excel['ms'] == 12:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_2.setCurrentText(page['ms3'])
                else:
                    self.comboBox_2.setCurrentText("SAE40")
            elif self.data.excel['ms'] == 16:
                if data['lang'] != "":
                    page = data['en']['page5']
                    self.comboBox_2.setCurrentText(page['ms4'])
                else:
                    self.comboBox_2.setCurrentText("SAE50")
            self.comboBox_2.blockSignals(False)
        except:
            pass
        self.tableWidget.blockSignals(True)
        self.comboBox_2.currentIndexChanged.connect(self.sae_choice)
        self.comboBox_3.currentIndexChanged.connect(self.availability)
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][0]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Температура масла в масляной магистрали (в картере); tvx"))
        try:
            value = str(self.data.excel['tvx'])
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        self.tableWidget.setItem(row, 1, QTableWidgetItem('°С'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][1]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметр смазочного отверстия шатунной шейки; d0"))
        try:
            value = str(self.data.excel['d0']) if self.data.excel['d0'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][2]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Количество смазочных отверстий в шатунной шейке; -"))
        try:
            value = str(self.data.excel['-']) if self.data.excel['-'] != None else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        self.tableWidget.setItem(row, 1, QTableWidgetItem('-'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][3]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения смазочного отверстия в шатунной шейке; TETAP1"))
        try:
            value = str(self.data.excel['TETAP1']) if self.data.excel['TETAP1'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][4]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения смазочного отверстия в шатунной шейке; TETAP2"))
        try:
            value = str(self.data.excel['TETAP2']) if self.data.excel['TETAP2'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][5]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения смазочного отверстия в коренной  шейке; TETAF1"))
        try:
            value = str(self.data.excel['TETAF1']) if self.data.excel['TETAF1'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][6]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения смазочного отверстия в коренной  шейке; TETAF2"))
        try:
            value = str(self.data.excel['TETAF2']) if self.data.excel['TETAF2'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))


        # self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        # self.tableWidget.setItem(row, 1, QTableWidgetItem('град.'))


        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][7]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор шатунного подшипника; ssch"))
        try:
            value = str(self.data.excel['ssch']) if self.data.excel['ssch'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][8]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор коренного подшипника; skor"))
        try:
            value = str(self.data.excel['skor']) if self.data.excel['skor'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][9]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Предельно-допустимая пленка для шатунного подшипника; fks"))
        try:
            value = str(self.data.excel['fks']) if self.data.excel['fks'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][10]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Предельно-допустимая пленка для коренного подшипника; fkk"))
        try:
            value = str(self.data.excel['fkk']) if self.data.excel['fkk'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][11]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор шатунного подшипника для теплового расчета; sscht"))
        try:
            value = str(self.data.excel['sscht']) if self.data.excel['sscht'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))

        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        if data['lang'] != "":
            page = data['en']['page5']
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][12]))
        else:
            self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор коренного подшипника для теплового расчета; skort"))
        try:
            value = str(self.data.excel['skort']) if self.data.excel['skort'] else ""
        except:
            value = ""

        self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
        if data['lang'] != "":
            self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
        else:
            self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))
        self.tableWidget.blockSignals(False)
        self.tableWidget.cellChanged.connect(self.cellChange)

    # def handleActivated(self, index):
    #     with open('lang.json', encoding='utf-8') as file:
    #         data = json.load(file)
    #     self.lw = self.comboBox_3.currentData()
    #     # excel = ReadExcel(self.filename)
    #     self.expert.excel['lw'] = self.lw
    #     # excel.updateCell('lw', self.lw, self.filename)
    #     if self.lw == 1:
    #         row = self.tableWidget.rowCount()
    #         self.tableWidget.insertRow(row)
    #         if data['lang'] != "":
    #             page = data['en']['page5']
    #             self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][12]))
    #         else:
    #             self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор шатунного подшипника для теплового расчета; sscht"))
    #         try:
    #             value = str(self.data.excel['sscht']) if self.data.excel['sscht'] else ""
    #         except:
    #             value = ""

    #         self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
    #         if data['lang'] != "":
    #             self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
    #         else:
    #             self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))

    #         row = self.tableWidget.rowCount()
    #         self.tableWidget.insertRow(row)
    #         if data['lang'] != "":
    #             page = data['en']['page5']
    #             self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][13]))
    #         else:
    #             self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Диаметральный зазор коренного подшипника для теплового расчета; skort"))
    #         try:
    #             value = str(self.data.excel['skort']) if self.data.excel['skort'] else ""
    #         except:
    #             value = ""

    #         self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
    #         if data['lang'] != "":
    #             self.tableWidget.setItem(row, 1, QTableWidgetItem('mm'))
    #         else:
    #             self.tableWidget.setItem(row, 1, QTableWidgetItem('мм'))
    #     else:
    #         row = self.tableWidget.rowCount()-1
    #         self.tableWidget.removeRow(row)
    #         row = self.tableWidget.rowCount()-1
    #         self.tableWidget.removeRow(row)
    def sae_choice(self, index):
        self.sae = self.comboBox_2.currentData()
        self.data.excel['ms'] = self.sae
        self.expert.excel['ms'] = self.sae
        # excel = ReadExcel(self.filename)
        # excel.updateCell('ms', self.sae, self.filename)
    def construct(self, index):
        groove = self.comboBox.currentData()
        # self.data.excel['nw'] = groove
        # self.expert.excel['nw'] = groove
        if groove == 3:
            self.data.groove = "PART"
            self.data.excel['nw'] = 2
            self.expert.excel['nw'] = 2
        elif groove == 2:
            self.data.groove = "PART"
            self.data.excel['nw'] = 2 #2
            self.expert.excel['nw'] = 2 #2
        elif groove == 1:
            self.data.groove = "FULL"
            self.data.excel['nw'] = 1
            self.expert.excel['nw'] = 1
        elif groove == 0:
            self.data.groove = "NO"
            self.data.excel['nw'] = 0
            self.expert.excel['nw'] = 0
        # excel = ReadExcel(self.filename)
        # excel.updateCell('nw', self.comboBox.currentData(), self.filename)
    def availability(self, index):
        self.data.excel['lw'] = self.comboBox_3.currentData()
        self.expert.excel['lw'] = self.comboBox_3.currentData()
        # excel = ReadExcel(self.filename)
        # excel.updateCell('lw', self.comboBox_3.currentData(), self.filename)
    def cellChange(self, row, column):
        key = self.tableWidget.verticalHeaderItem(row).text().split('; ')[1]
        if validation(self.tableWidget.item(row, column).text(), key, self.data.excel):
            self.tableWidget.blockSignals(True)
            self.tableWidget.item(row, column).setBackground(QtGui.QColor(112, 255, 127))
            self.tableWidget.blockSignals(False)
            self.expert.excel[key] = self.tableWidget.item(row, column).text()
            self.data.excel[key] = self.tableWidget.item(row, column).text()
            # excel = ReadExcel(self.filename)
            # excel.updateCell(key, self.tableWidget.item(row, column).text(), self.filename)
            try:
                if self.err.error_dict[key] > 0:
                    del self.err.error_dict[key]
            except:
                pass
        else:
            self.tableWidget.blockSignals(True)
            self.tableWidget.item(row, column).setBackground(QtGui.QColor(255, 152, 152))
            self.tableWidget.blockSignals(False)
            self.err.error_dict[key] = 5
            self.err.page = 5